from alipay import AliPay
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from orders.models import OrderInfo
from meiduo_mall.utils.response_code import RET


# Create your views here.
from payment.models import Payment


class MyLoginRequiredMiXinView(LoginRequiredMixin, View):
    login_url = "/login/"


class AlipayView(MyLoginRequiredMiXinView):
    def get(self, request, order_id):

        try:
            order = OrderInfo.objects.get(order_id=order_id)

        except Exception as e:
            return HttpResponseForbidden("非法请求...")

        app_private_key_string = open(settings.APP_PRIVATE_KEY).read()
        alipay_public_key_string = open(settings.APLIPAY_PUBLIC_KEY).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False  # 默认False
        )

        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount + order.freight),
            subject="美多商城订单%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        alipay_url = settings.ALIPAY_URL + order_string

        return JsonResponse({"code": RET.OK, "alipay_url": alipay_url})


class PaymentStatusView(MyLoginRequiredMiXinView):

    def get(self, request):

        # 获取参数
        result_dict = request.GET.dict()

        # 校验参数
        # 创建alipay对象
        app_private_key_string = open(settings.APP_PRIVATE_KEY).read()
        alipay_public_key_string = open(settings.APLIPAY_PUBLIC_KEY).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False  # 默认False
        )

        # 参数校验
        signature = result_dict.pop("sign")
        success = alipay.verify(result_dict, signature)

        if not success:
            return HttpResponseForbidden("交易失败...")

        # 数据入库
        # 写入订单号和流水号码
        order_id = result_dict.get("out_trade_no")
        trade_id = result_dict.get("trade_no")
        new_payment = Payment.objects.create(order=OrderInfo.objects.get(order_id=order_id), trade_id=trade_id)

        # 订单状态改成未评论状态
        new_payment.order.status = OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"]
        new_payment.order.save()

        # 返回响应
        context = {"order_id": order_id}
        return render(request, "pay_success.html", context=context)
